var router = require('express').Router();
var crypto = require('crypto');
var https = require('https');
var xml2js = require('xml2js');
var xmlParser = require('express-xml-bodyparser');
var utils = require('../util/utils');
var _ = require('underscore');
var config = require('../config/WXConfig');
var WXService = require('./WXService');
var WXApi = require('../lib/WXApi');
var redisClient = require('../redis').redisClient;
var AV = require('leanengine');
var WeiXinUserInfo = AV.Object.extend('WeiXinUserInfo');


/* 清空 access_token 和 jsapi_ticket*/
router.get('/cleanRedis', function (req, res, next) {
    redisClient.del(config.ACCESS_TOKEN_NAME,config.JSAPI_TICKET_NAME,function(data1,data2){
        res.send({
            data1:data1,
            data2:data2
        });
    });
});

/* 清空 access_token 和 jsapi_ticket*/
router.get('/cleanWeiXinUser', function (req, res, next) {
    var query = new AV.Query('WeiXinUserInfo');
    query.limit(1000);
    query.find().then(function (data) {
        AV.Object.destroyAll(data);
        res.send('删除成功');
    });

});

router.get('/allUsers', function (req, res, next) {
    var query = new AV.Query('WeiXinUserInfo');
    var afterSept = new Date('2016-12-3 16:00');
    query.greaterThan('subscribe_time', afterSept);
    query.limit(1000);
    query.find().then(function (datas) {
        res.send(_.map(datas, function (item) {
            return {
                headimgurl: item.get('headimgurl'),
                nickname: item.get('nickname'),
                openid: item.get('openid')
            }
        }));
    });
});

router.get('/batchUserInfo', function (req, res, next) {
    WXService.batchGetOpenids(function (err, data) {
        if (err) {
            res.send(err);
        }
        else {
            console.log('all openids length: ' + data.length);

            var hundredDataArr = [];
            var index = 0;
            while (index < data.length) {
                if (index + 100 < data.length) {
                    hundredDataArr.push(data.slice(index, index + 100));
                }
                else {
                    hundredDataArr.push(data.slice(index, data.length));
                }
                index += 100;
            }

            for (var i = 0; i < hundredDataArr.length; i++) {
                (function (hundredData) {
                    console.log('hundredData length :' + hundredData.length);
                    WXService.batchUserInfo(hundredData, function (err, data) {
                        if (data && data.user_info_list) {
                            var weiXinUsers = _.map(data.user_info_list, function (item) {
                                return transfor(item);
                            });
                            AV.Object.saveAll(weiXinUsers);
                        }
                    });

                    console.log('=========');

                })(hundredDataArr[i]);
            }
        }

        res.send('数据处理中');
    });

});

function transfor(data) {
    var weixinUserInfo = new WeiXinUserInfo();
    weixinUserInfo.set('subscribe', data.subscribe + "");
    weixinUserInfo.set('openid', data.openid);
    weixinUserInfo.set('nickname', data.nickname);
    weixinUserInfo.set('sex', data.sex + '');
    weixinUserInfo.set('city', data.city);
    weixinUserInfo.set('province', data.province);
    weixinUserInfo.set('headimgurl', data.headimgurl);
    weixinUserInfo.set('subscribe_time', new Date(data.subscribe_time * 1000));
    return weixinUserInfo;
}

/*
 {
 "type": "text",
 "message": {
 "ToUserName": "toUser",
 "FromUserName": "fromUser",
 "CreateTime": "1348831860",
 "MsgType": "text",
 "Content": "this is a test",
 "MsgId": "1234567890123456"
 }
 }
 * */
//微信接入的url POST 获取message 消息
router.post('/', xmlParser({trim: true, explicitArray: false, normalizeTags:false}), function (req, res) {
    console.log('receive message from post request');
    WXService.receiveMessage(req.body, function (messageType, message) {
        res.set('Content-Type', 'text/xml');
        switch (messageType) {
            case config.RECEIVED_MESSAGE_TYPE.EVENT_SUBSCRIBE:
                var xml = getMessage(messageType, message);
                res.send(xml);
                break;
            case config.RECEIVED_MESSAGE_TYPE.EVENT_UNSUBSCRIBE:
                var xml = getMessage(messageType, message);
                res.send(xml);
                break;
            case config.RECEIVED_MESSAGE_TYPE.TEXT:
                var xml = getMessage(messageType, message);
                res.send(xml);
                break;
            default:
                console.log('send default message');
                res.send('');
        }
    });
});

//被动发送消息
function getMessage(messageType, message) {
    var params = {};
    params.xml = {
        ToUserName: message.FromUserName,
        FromUserName: message.ToUserName,
        CreateTime: new Date().getTime(),
        MsgType: 'text',
        Content: 'receive message Type :' + messageType
    }
    var builder = new xml2js.Builder();
    return builder.buildObject(params);
}

// 接入微信服务器
router.get('/', function (req, res, next) {
    var params = req.query;
    WXService.checkSignature(params.signature, params.timestamp, params.nonce, params.echostr, function (error, result) {
        res.send(result || error);
    });
});

/* 获取接口 access_token */
router.get('/getAccessToken', function (req, res, next) {
    WXService.getAccessToken(function (error, accessToken) {
        res.send({
            error: error,
            data: accessToken
        });
    })
});

module.exports = router;